package com.gmadmin.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmadmin.common.ApiResponse;
import com.gmadmin.entity.SysMenu;
import com.gmadmin.entity.dto.SysMenuDto;
import com.gmadmin.payload.MenuQueryCriteria;
import com.gmadmin.service.SysMenuService;
import com.gmadmin.entity.vo.menu.NavMenuVo;
import com.gmadmin.utils.SecurityUtils;
import com.gmadmin.entity.vo.menu.SysMenuVo;
import com.gmadmin.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/12/31 13:27
 * /菜单
 */
@Api(tags = "系统:菜单管理")
@RequestMapping("/api/system/menu")
@RestController
public class SysMenuController {

    private final SysMenuService service;

    private Logger logger = LoggerFactory.getLogger(SysMenuController.class);

    public SysMenuController(SysMenuService service) {
        this.service = service;
    }


    @ApiOperation(value = "导航菜单")
    @GetMapping(value = "/nav/build")
    public ApiResponse<List<NavMenuVo>> buildNavMenu() {
        List<SysMenuVo> menuVoList = service.findListByUserId(SecurityUtils.getCurrentUserId());
        List<SysMenuVo> menuVosTree = service.buildTree(menuVoList.stream().filter(m -> m.getType() != 2).collect(Collectors.toList()));
        return ApiResponse.ofSuccess(service.buildMenus(menuVosTree));
    }

    @ApiOperation(value = "菜单树")
    @GetMapping("tree")
    public ApiResponse<List<SysMenuVo>> findTree() {
        return ApiResponse.ofSuccess(service.findTree());
    }

    @ApiOperation(value = "分页查询菜单")
    @GetMapping(value = "page")
    public ApiResponse<PageVo<List<SysMenuVo>>> findMenuListByPage(MenuQueryCriteria criteria, Page<SysMenu> page) {
        return ApiResponse.ofSuccess((PageVo<List<SysMenuVo>>) service.findListByPage(criteria, page));
    }

    @ApiOperation(value = "根据pid查询当前菜单子节点")
    @GetMapping(value = "/{pid:\\d+}")
    public ApiResponse<List<SysMenuVo>> findMenuListByPid(@PathVariable(value = "pid") Long pid) {
        List<SysMenuVo> sysMenuVos = service.findListByPid(pid);
        return ApiResponse.ofSuccess(sysMenuVos);
    }

    @ApiOperation(value = "新增或者修改菜单")
    @PostMapping
    public ApiResponse saveOrUpdateMenu(@RequestBody SysMenuDto menuDto) {
        service.saveOrUpdate(BeanUtil.copyProperties(menuDto, SysMenu.class));
        return ApiResponse.ofSuccess();
    }

    @ApiOperation(value = "删除菜单,逻辑删除")
    @DeleteMapping
    public ApiResponse deleteMenu(@RequestParam("id") Long id) {
        service.removeById(id);
        return ApiResponse.ofSuccess();
    }
}
